package view.admin;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 系统设置面板
 */
public class SystemSettingsPanel extends JPanel {
    private JSpinner maxReservationDaysSpinner;
    private JSpinner maxReservationHoursSpinner;
    private JCheckBox allowCancelCheckBox;
    private JSpinner cancelDeadlineSpinner;
    private JTextArea noticeTextArea;
    private JButton saveSettingsButton;
    private JButton resetSettingsButton;

    public SystemSettingsPanel() {
        initComponents();
        setupLayout();
        setupEventListeners();
        loadSettings();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        // 设置控件
        maxReservationDaysSpinner = new JSpinner(new SpinnerNumberModel(7, 1, 30, 1));
        maxReservationHoursSpinner = new JSpinner(new SpinnerNumberModel(4, 1, 12, 1));
        allowCancelCheckBox = new JCheckBox("允许用户取消预约", true);
        cancelDeadlineSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 24, 1));

        noticeTextArea = new JTextArea(5, 30);
        noticeTextArea.setLineWrap(true);
        noticeTextArea.setWrapStyleWord(true);
        noticeTextArea.setText("欢迎使用自习室座位预约系统！\n请遵守自习室规章制度，保持安静学习环境。");

        saveSettingsButton = new JButton("保存设置");
        resetSettingsButton = new JButton("重置为默认");

        // 美化组件
        styleSpinner(maxReservationDaysSpinner);
        styleSpinner(maxReservationHoursSpinner);
        styleSpinner(cancelDeadlineSpinner);
        styleCheckBox(allowCancelCheckBox);
        styleTextArea(noticeTextArea);
        styleButton(saveSettingsButton, new Color(34, 197, 94), Color.WHITE);
        styleButton(resetSettingsButton, new Color(245, 158, 11), Color.WHITE);
    }

    private void setupLayout() {
        // 主容器
        JPanel mainContainer = new JPanel(new BorderLayout());
        mainContainer.setBackground(new Color(248, 250, 252));

        // 顶部面板 - 包含标题和操作按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(248, 250, 252));
        topPanel.setBorder(BorderFactory.createEmptyBorder(30, 0, 20, 0));

        // 标题
        JLabel titleLabel = new JLabel("系统设置", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        titleLabel.setForeground(new Color(75, 85, 99));

        // 右上角按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 0));
        buttonPanel.setBackground(new Color(248, 250, 252));
        buttonPanel.add(saveSettingsButton);
        buttonPanel.add(resetSettingsButton);

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.EAST);

        // 内容面板 - 使用FlowLayout让卡片有固定宽度
        JPanel contentPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        contentPanel.setBackground(new Color(248, 250, 252));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 30, 30, 30));

        // 三个卡片：预约设置、系统公告、时间段设置
        JPanel reservationCard = createReservationSettingsCard();
        JPanel noticeCard = createNoticeCard();
        JPanel timeSlotCard = createTimeSlotPanel();

        contentPanel.add(reservationCard);
        contentPanel.add(noticeCard);
        contentPanel.add(timeSlotCard);

        mainContainer.add(topPanel, BorderLayout.NORTH);
        mainContainer.add(contentPanel, BorderLayout.CENTER);

        // 添加滚动支持
        JScrollPane scrollPane = new JScrollPane(mainContainer);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getViewport().setBackground(new Color(248, 250, 252));

        add(scrollPane, BorderLayout.CENTER);
    }

    private JPanel createReservationSettingsCard() {
        JPanel card = new JPanel();
        card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
        card.setBackground(new Color(255, 255, 255));
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(25, 25, 25, 25)));

        // 卡片标题
        JLabel cardTitle = new JLabel("预约设置");
        cardTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        cardTitle.setForeground(new Color(55, 65, 81));
        card.add(cardTitle);
        card.add(Box.createVerticalStrut(20));

        // 最大预约天数
        JLabel daysLabel = createFieldLabel("最大提前预约天数");
        card.add(daysLabel);
        card.add(Box.createVerticalStrut(5));

        JPanel daysPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        daysPanel.setBackground(new Color(255, 255, 255));
        daysPanel.add(maxReservationDaysSpinner);
        daysPanel.add(Box.createHorizontalStrut(10));
        daysPanel.add(new JLabel("天"));
        card.add(daysPanel);
        card.add(Box.createVerticalStrut(15));

        // 最大预约时长
        JLabel hoursLabel = createFieldLabel("单次最大预约时长");
        card.add(hoursLabel);
        card.add(Box.createVerticalStrut(5));

        JPanel hoursPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        hoursPanel.setBackground(new Color(255, 255, 255));
        hoursPanel.add(maxReservationHoursSpinner);
        hoursPanel.add(Box.createHorizontalStrut(10));
        hoursPanel.add(new JLabel("小时"));
        card.add(hoursPanel);
        card.add(Box.createVerticalStrut(15));

        // 取消预约设置
        card.add(allowCancelCheckBox);
        card.add(Box.createVerticalStrut(10));

        JLabel deadlineLabel = createFieldLabel("取消截止时间");
        card.add(deadlineLabel);
        card.add(Box.createVerticalStrut(5));

        JPanel deadlinePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        deadlinePanel.setBackground(new Color(255, 255, 255));
        deadlinePanel.add(cancelDeadlineSpinner);
        deadlinePanel.add(Box.createHorizontalStrut(10));
        deadlinePanel.add(new JLabel("小时前"));
        card.add(deadlinePanel);

        // 设置卡片固定宽度
        card.setPreferredSize(new Dimension(320, 400));
        card.setMaximumSize(new Dimension(320, 400));

        return card;
    }

    private JPanel createNoticeCard() {
        JPanel card = new JPanel(new BorderLayout());
        card.setBackground(new Color(255, 255, 255));
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(25, 25, 25, 25)));

        // 卡片标题
        JLabel cardTitle = new JLabel("系统公告");
        cardTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        cardTitle.setForeground(new Color(55, 65, 81));
        card.add(cardTitle, BorderLayout.NORTH);

        // 公告文本区域
        JScrollPane noticeScrollPane = new JScrollPane(noticeTextArea);
        noticeScrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        noticeScrollPane.getViewport().setBackground(new Color(255, 255, 255));

        JPanel scrollContainer = new JPanel(new BorderLayout());
        scrollContainer.setBackground(new Color(255, 255, 255));
        scrollContainer.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
        scrollContainer.add(noticeScrollPane, BorderLayout.CENTER);

        card.add(scrollContainer, BorderLayout.CENTER);

        // 设置卡片固定宽度
        card.setPreferredSize(new Dimension(320, 400));
        card.setMaximumSize(new Dimension(320, 400));

        return card;
    }

    private JLabel createFieldLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(107, 114, 128));
        return label;
    }

    private JPanel createTimeSlotPanel() {
        JPanel card = new JPanel(new BorderLayout());
        card.setBackground(new Color(255, 255, 255));
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(25, 25, 25, 25)));

        // 卡片标题
        JLabel cardTitle = new JLabel("时间段设置");
        cardTitle.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        cardTitle.setForeground(new Color(55, 65, 81));
        card.add(cardTitle, BorderLayout.NORTH);

        // 时间段设置区域 - 三列并排布局
        JPanel timePanel = new JPanel(new GridLayout(1, 3, 15, 0));
        timePanel.setBackground(new Color(255, 255, 255));
        timePanel.setBorder(BorderFactory.createEmptyBorder(25, 5, 0, 5));

        // 创建三个时段的设置面板
        timePanel.add(createTimeSlotSection("上午时段"));
        timePanel.add(createTimeSlotSection("下午时段"));
        timePanel.add(createTimeSlotSection("晚上时段"));

        card.add(timePanel, BorderLayout.CENTER);

        // 设置卡片固定宽度
        card.setPreferredSize(new Dimension(320, 400));
        card.setMaximumSize(new Dimension(320, 400));

        return card;
    }

    /**
     * 创建单个时间段设置区域
     */
    private JPanel createTimeSlotSection(String title) {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS));
        section.setBackground(new Color(255, 255, 255));

        // 时段标题
        JLabel titleLabel = createFieldLabel(title);
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        section.add(titleLabel);
        section.add(Box.createVerticalStrut(12));

        // 创建时间选择器
        JSpinner startSpinner = new JSpinner(new SpinnerDateModel());
        startSpinner.setEditor(new JSpinner.DateEditor(startSpinner, "HH:mm"));
        styleSpinner(startSpinner);
        startSpinner.setMaximumSize(new Dimension(100, 35));
        startSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);

        JSpinner endSpinner = new JSpinner(new SpinnerDateModel());
        endSpinner.setEditor(new JSpinner.DateEditor(endSpinner, "HH:mm"));
        styleSpinner(endSpinner);
        endSpinner.setMaximumSize(new Dimension(100, 35));
        endSpinner.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 布局：开始时间 - 分隔符 - 结束时间
        section.add(startSpinner);
        section.add(Box.createVerticalStrut(10));

        JLabel separator = new JLabel("—");
        separator.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        separator.setForeground(new Color(107, 114, 128));
        separator.setAlignmentX(Component.CENTER_ALIGNMENT);
        section.add(separator);

        section.add(Box.createVerticalStrut(10));
        section.add(endSpinner);

        return section;
    }

    private void setupEventListeners() {
        saveSettingsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveSettings();
            }
        });

        resetSettingsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetToDefault();
            }
        });

        allowCancelCheckBox.addActionListener(_ -> {
            cancelDeadlineSpinner.setEnabled(allowCancelCheckBox.isSelected());
        });
    }

    private void loadSettings() {
        // 这里可以从数据库或配置文件加载设置
        // 目前使用默认值
    }

    private void saveSettings() {
        try {
            // 获取设置值
            int maxDays = (Integer) maxReservationDaysSpinner.getValue();
            int maxHours = (Integer) maxReservationHoursSpinner.getValue();
            boolean allowCancel = allowCancelCheckBox.isSelected();
            int cancelDeadline = (Integer) cancelDeadlineSpinner.getValue();
            String notice = noticeTextArea.getText();

            // 这里应该保存到数据库
            // systemController.saveSettings(maxDays, maxHours, allowCancel, cancelDeadline,
            // notice);
            System.out.println("保存设置: 最大天数=" + maxDays + ", 最大时长=" + maxHours + ", 允许取消=" + allowCancel + ", 取消截止="
                    + cancelDeadline + "小时前, 公告=" + notice.length() + "字符");

            JOptionPane.showMessageDialog(this, "设置保存成功!", "成功", JOptionPane.INFORMATION_MESSAGE);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "保存设置失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void resetToDefault() {
        int option = JOptionPane.showConfirmDialog(this, "确定要重置为默认设置吗？",
                "确认重置", JOptionPane.YES_NO_OPTION);

        if (option == JOptionPane.YES_OPTION) {
            maxReservationDaysSpinner.setValue(7);
            maxReservationHoursSpinner.setValue(4);
            allowCancelCheckBox.setSelected(true);
            cancelDeadlineSpinner.setValue(2);
            noticeTextArea.setText("欢迎使用自习室座位预约系统！\n请遵守自习室规章制度，保持安静学习环境。");
        }
    }

    /**
     * 美化Spinner样式
     */
    private void styleSpinner(JSpinner spinner) {
        spinner.setPreferredSize(new Dimension(80, 32));
        spinner.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        spinner.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(5, 8, 5, 8)));

        // 设置编辑器样式
        JComponent editor = spinner.getEditor();
        if (editor instanceof JSpinner.DefaultEditor) {
            JTextField textField = ((JSpinner.DefaultEditor) editor).getTextField();
            textField.setBackground(new Color(255, 255, 255));
            textField.setBorder(BorderFactory.createEmptyBorder());
        }
    }

    /**
     * 美化CheckBox样式
     */
    private void styleCheckBox(JCheckBox checkBox) {
        checkBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        checkBox.setBackground(new Color(255, 255, 255));
        checkBox.setForeground(new Color(55, 65, 81));
        checkBox.setFocusPainted(false);
        checkBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }

    /**
     * 美化TextArea样式
     */
    private void styleTextArea(JTextArea textArea) {
        textArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textArea.setBackground(new Color(255, 255, 255));
        textArea.setForeground(new Color(55, 65, 81));
        textArea.setBorder(BorderFactory.createEmptyBorder(10, 12, 10, 12));
        textArea.setCaretColor(new Color(59, 130, 246));
    }

    /**
     * 美化按钮样式
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 16, 8, 16)));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }
}
